package org.linlinjava.litemall.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.linlinjava.litemall.db.dao.PermissionMapper;
import org.linlinjava.litemall.db.models.Permission;
import org.linlinjava.litemall.db.service.PermissionService;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService {

    @Override
    public Set<String> queryByRoleIds(Integer[] roleIds) {
        Set<String> permissions = new HashSet<String>();
        if(roleIds.length == 0){
            return permissions;
        }
        QueryWrapper<Permission> query = new QueryWrapper<>();
        query.eq("deleted", false);
        query.in("role_id", Arrays.asList(roleIds));
        List<Permission> permissionList = this.baseMapper.selectList(query);

        for(Permission permission : permissionList){
            permissions.add(permission.getPermission());
        }
        return permissions;
    }

    @Override
    public Set<String> queryByRoleId(Integer roleId) {
        return this.queryByRoleIds(new Integer[]{roleId});
    }

    @Override
    public boolean checkSuperPermission(Integer roleId) {
        if(roleId == null){
            return false;
        }
        QueryWrapper<Permission> query = new QueryWrapper<>();
        query.eq("deleted", false);
        query.eq("role_id", roleId);
        query.eq("permission", "*");
        return this.baseMapper.selectCount(query) > 0;
    }

    @Override
    public void deleteByRoleId(Integer roleId) {
        QueryWrapper<Permission> query = new QueryWrapper<>();
        query.eq("deleted", true);
        query.eq("role_id", roleId);
        this.baseMapper.delete(query);
    }

}
